package com.ruoyi.project.mobile.upload;

import java.io.File;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.ruoyi.common.utils.R;
import com.ruoyi.common.utils.RFactory;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.qiniu.QiNiuUploadUtil;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.AppBeanInjector;

/**
 * 功能：
 *
 * @author：dell
 * @create：2020/6/29 9:05
 * @version：2020 Version：1.0
 * @company：老屋新房 Created with IntelliJ IDEA
 */
@RestController
@RequestMapping("/api/upload")
public class ApiUploadController {

	@Autowired
	private ServerConfig serverConfig;
	/**
	 * 通用上传请求
	 */
	@PostMapping
	@ResponseBody
	public R uploadFile(MultipartFile file, @RequestParam(required = false) Integer type) throws Exception
	{
		try
		{
			String fileName = "";
			String url = "";
			if(type!=null){
				// 上传文件路径
				String filePath = RuoYiConfig.getUploadPath();
				StringBuffer fileRealName = new StringBuffer();
				fileName = FileUploadUtils.upload(filePath, file,fileRealName);
				url = serverConfig.getUrl()+fileName;
				String http= url.substring(0,5);
				if(!http.equals("https")){
					url=url.replaceFirst("http","https");
				}
			}else{
				fileName = FileUploadUtils.extractFilename(file);
				// 上传并返回新文件名称
				AppBeanInjector.qiniuUploadUtil.upload(file.getBytes(),fileName);
				url = QiNiuUploadUtil.getBaseUrl() + fileName;

			}
			AjaxResult ajax = AjaxResult.success();
			ajax.put("fileName", fileName);
			ajax.put("url", url);

			//文件上传成功以后生成upload_file数据
//			this.uploadFileService.insertUploadFile(new UploadFile(null,url,realPath,null));


			return RFactory.generateR(ajax);
		}
		catch (Exception e)
		{
			return R.error(e.getMessage());
		}
	}

}
